#!/usr/bin/env python3
"""
多账户逻辑简化示例
用最简单的代码展示多账户的核心逻辑
"""

import threading
import time
import json

# 模拟配置
CONFIG = {
    "accounts": {
        "demo": {
            "enabled": True,
            "sandbox": True,
            "symbols": ["BTC/USDT", "ETH/USDT"],
            "leverage": 10
        },
        "live": {
            "enabled": False,
            "sandbox": False,
            "symbols": ["BTC/USDT"],
            "leverage": 5
        }
    }
}

class SimpleTradingAccount:
    """简化的交易账户"""
    
    def __init__(self, account_id, config):
        self.account_id = account_id
        self.config = config
        self.running = False
        print(f"🤖 创建账户: {account_id}")
    
    def start(self):
        """启动账户"""
        print(f"🚀 启动账户: {self.account_id}")
        self.running = True
        
        # 启动交易循环线程
        thread = threading.Thread(target=self.trading_loop)
        thread.daemon = True
        thread.start()
        return True
    
    def trading_loop(self):
        """交易循环"""
        print(f"🎯 {self.account_id} 开始交易循环")
        
        while self.running:
            # 模拟交易逻辑
            for symbol in self.config["symbols"]:
                print(f"📊 {self.account_id} 分析 {symbol}")
                # 这里会调用真实的交易逻辑
                time.sleep(1)  # 模拟分析时间
            
            print(f"⏰ {self.account_id} 等待15分钟...")
            time.sleep(5)  # 实际是900秒(15分钟)
    
    def stop(self):
        """停止账户"""
        print(f"🛑 停止账户: {self.account_id}")
        self.running = False

class SimpleAccountManager:
    """简化的账户管理器"""
    
    def __init__(self):
        self.accounts = {}
        print("🏗️ 创建账户管理器")
    
    def start_all_accounts(self):
        """启动所有账户"""
        print("🚀 开始启动所有账户")
        
        # 找到启用的账户
        enabled_accounts = [
            account_id for account_id, config in CONFIG["accounts"].items()
            if config.get("enabled", False)
        ]
        
        print(f"📊 发现 {len(enabled_accounts)} 个启用的账户: {enabled_accounts}")
        
        # 启动每个账户
        for account_id in enabled_accounts:
            config = CONFIG["accounts"][account_id]
            account = SimpleTradingAccount(account_id, config)
            
            if account.start():
                self.accounts[account_id] = account
                print(f"✅ {account_id} 启动成功")
            else:
                print(f"❌ {account_id} 启动失败")
        
        print(f"🎯 所有账户启动完成，活跃账户: {list(self.accounts.keys())}")
    
    def run(self):
        """运行管理器"""
        try:
            # 启动所有账户
            self.start_all_accounts()
            
            # 主循环
            print("🎯 账户管理器运行中...")
            while True:
                time.sleep(1)
                
        except KeyboardInterrupt:
            print("👋 收到中断信号，正在关闭...")
            self.stop_all_accounts()
    
    def stop_all_accounts(self):
        """停止所有账户"""
        print("🛑 停止所有账户")
        for account in self.accounts.values():
            account.stop()
        self.accounts.clear()

def demonstrate_logic():
    """演示多账户逻辑"""
    
    print("=" * 60)
    print("🧪 多账户逻辑演示")
    print("=" * 60)
    
    print("\n1️⃣ 配置解析:")
    print(f"   配置文件: {json.dumps(CONFIG, indent=2, ensure_ascii=False)}")
    
    print("\n2️⃣ 筛选启用的账户:")
    enabled = [k for k, v in CONFIG["accounts"].items() if v.get("enabled")]
    print(f"   启用的账户: {enabled}")
    
    print("\n3️⃣ 创建账户管理器:")
    manager = SimpleAccountManager()
    
    print("\n4️⃣ 启动账户:")
    manager.start_all_accounts()
    
    print("\n5️⃣ 运行10秒演示:")
    try:
        time.sleep(10)
    except KeyboardInterrupt:
        pass
    
    print("\n6️⃣ 停止所有账户:")
    manager.stop_all_accounts()
    
    print("\n✅ 演示完成!")

if __name__ == "__main__":
    demonstrate_logic()
